<?php

/**
 * This is the model class for table "{{pages}}".
 *
 * The followings are the available columns in table '{{pages}}':
 * @property string $pageId
 * @property string $pageParent
 * @property string $pageType
 * @property string $pageUrl
 * @property string $pageTitle
 * @property string $pageContentShort
 * @property string $pageContentFull
 * @property string $pageImages
 * @property integer $pageActive
 * @property string $pageAuthor
 * @property integer $pageSort
 * @property string $pageAction
 * @property integer $pageItemId
 */
class Brand extends CActiveRecord {

	public $pageCategory;

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return '{{pages}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('pageUrl, pageTitle, pageActive', 'required'),
			array('pageParent', 'default'),
			array('pageImages', 'file', 'allowEmpty' => false, 'types' => 'jpg,png,bmp,jpeg', 'on' => 'create'),
			array('pageImages', 'file', 'allowEmpty' => true, 'types' => 'jpg,png,bmp,jpeg', 'on' => 'update'),
//			array('pageActive, pageSort, pageItemId', 'numerical', 'integerOnly'=>true),
//			array('pageParent, pageAuthor', 'length', 'max'=>11),
//			array('pageType', 'length', 'max'=>8),
//			array('pageUrl, pageTitle, pageImages, pageAction', 'length', 'max'=>255),
//			array('pageContentShort, pageContentFull', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('pageId, pageParent, pageType, pageUrl, pageTitle, pageContentShort, pageContentFull, pageImages, pageActive, pageAuthor, pageSort, pageAction, pageItemId', 'safe', 'on' => 'search'),
		);
	}

	public function getBrands() {

		$array = array();

		$query = 'select b."pageId", (select c."pageTitle" from mb_pages c where c."pageId" =b."pageParent" ) ||  \' > \' || b."pageTitle" as "pageTitle" FROM mb_pages b where b."pageType"=\'brand\'';
		$brands = Yii::app()->db->createCommand($query)->queryAll();

		foreach ($brands as $brand) {
			$array[$brand['pageId']] = $brand['pageTitle'];
		}

		return $array;
	}

	public function getCategoryToBrand($pageParent) {
		$models = Page::model()->findAll("\"pageId\" = '" . (int) $pageParent . "'");
		$str = '';
		foreach ($models as $model) {
			$str .= '"' . $model['pageId'] . '" ,';
		}
		return substr($str, 0, strlen($str) - 1);
	}

	public function getProductCategory() {
		return json_encode(Yii::app()->db->createCommand("SELECT \"pageId\" as id, \"pageTitle\" as title FROM {{pages}} WHERE \"pageType\" = 'category'")->queryAll(true), 1);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations() {
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array(
			'pageId' => 'ID',
			'pageParent' => 'Родительская бренд',
			'pageType' => 'Page Type',
			'pageUrl' => 'Адрес бренда',
			'pageTitle' => 'Название',
			'pageContentShort' => 'Page Content Short',
			'pageContentFull' => 'Page Content Full',
			'pageImages' => 'Изображение',
			'pageActive' => 'Активность',
			'pageAuthor' => 'Page Author',
			'pageCategory' => 'Категория',
			'pageAction' => 'Page Action',
			'pageItemId' => 'Page Item',
		);
	}

	public function getDropdownItems($parentId = 0, $level = 0) {
		$itemsFormatted = array();
		$items = $this->model()->findAllByAttributes(array(
			'pageParent' => $parentId,
			'pageType' => 'brand',
		));
		foreach ($items as $item) {
			$itemsFormatted[$item->pageId] = str_repeat('&nbsp;&nbsp;', $level) . $item->pageTitle;
			$itemsFormatted = $itemsFormatted + $this->getDropdownItems($item->pageId, $level + 1);
		}
		return $itemsFormatted;
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search() {
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria = new CDbCriteria;

		$criteria->compare('"pageId"', $this->pageId);
		$criteria->compare('"pageParent"', $this->pageParent, true);
		$criteria->compare('"pageType"', $this->pageType, true);
		$criteria->compare('"pageUrl"', $this->pageUrl, true);
		$criteria->compare('"pageTitle"', $this->pageTitle, true);
		$criteria->compare('"pageContentShort"', $this->pageContentShort, true);
		$criteria->compare('"pageContentFull"', $this->pageContentFull, true);
		$criteria->compare('"pageImages"', $this->pageImages, true);
		$criteria->compare('"pageActive"', $this->pageActive);
		$criteria->compare('"pageAuthor"', $this->pageAuthor, true);
		$criteria->compare('"pageSort"', $this->pageSort);
		$criteria->compare('"pageAction"', $this->pageAction, true);
		$criteria->compare('"pageItemId"', $this->pageItemId);

		$criteria->addCondition("(\"pageType\" = 'brand' OR \"pageType\" = 'model')");
		return new CActiveDataProvider($this, array(
			'criteria' => $criteria,
			'pagination' => array(
				'pageSize' => 20,
				'pageVar' => 'page'
			),
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Brand the static model class
	 */
	public static function model($className = __CLASS__) {
		return parent::model($className);
	}

	public function beforeSave() {
		if (parent::beforeSave()) {
			$this->pageItemId = $this->pageId;
			if ($this->pageParent > 0) {
				$this->pageType = 'model';
				$this->pageAction = 'list/model';
				$parent = $this->model()->findByPk($this->pageParent);
				if ($this->isNewRecord)
					$this->pageUrl = $parent->pageUrl . '/' . $this->pageUrl;
			} else {
				$this->pageType = 'brand';
				$this->pageAction = 'list/brand';
				if (isset($_POST['Brand']['pageCategory'])) {
					$arrayCat = json_decode($_POST['Brand']['pageCategory']);
					//print_r($arrayCat);exit;
					if (empty($arrayCat))
						return false;
					$this->pageParent = $arrayCat[0];
					$a = $arrayCat[0];
					unset($arrayCat[0]);
					foreach ($arrayCat as $key => $value) {
						$parent = $this->model()->findByPk($value);
						$url = $parent->pageUrl . '/' . $this->pageUrl;
						$sql = "INSERT INTO {{pages}} (\"pageType\", \"pageAction\", \"pageParent\", \"pageUrl\", \"pageImages\", \"pageTitle\", \"pageItemId\") VALUES ('$this->pageType' , '$this->pageAction', '$value', '$url', '$this->pageImages', '$this->pageTitle', '$this->pageId') ";
						Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->query();
					}
					//$this->pageUrl = $this->model()->findByPk($a)->pageUrl . '/' . $this->pageUrl;
				}
			}
			$uploadedFile = CUploadedFile::getInstance($this, 'pageImages');
			if ($uploadedFile !== NULL) {
				if (!$this->isNewRecord) {
					if (file_exists("uploads/images/" . $this->pageType . "/" . $this->pageImages) && !empty($this->pageImages)) {
						unlink("uploads/images/" . $this->pageType . "/" . $this->pageImages);
						mTools::clearThumbImages(mTools::findFile('uploads/images/' . $this->pageType . '/thumbs/', pathinfo($file, PATHINFO_FILENAME), 'jpg'));
					}
				}
				$newFileName = getUrl::cleanString($this->pageTitle) . '.' . pathinfo($uploadedFile->name, PATHINFO_EXTENSION);
				copy($uploadedFile->tempName, 'uploads/images/' . $this->pageType . '/' . $newFileName);
				$this->pageImages = $newFileName;
			}
			if (isset($_POST['pageLinkedServices'])) {
				$this->pageLinkedServices = implode(',', json_decode($_POST['pageLinkedServices']));
			}

			return true;
		}
		return FALSE;
	}

	protected function afterDelete() {
		parent::afterDelete();
		if (file_exists("uploads/images/" . $this->pageType . "/" . $this->pageImages) && !empty($this->pageImages)){
			unlink("uploads/images/" . $this->pageType . "/" . $this->pageImages);
			mTools::clearThumbImages(mTools::findFile('uploads/images/' . $this->pageType . '/thumbs/', pathinfo($file, PATHINFO_FILENAME), 'jpg'));
		}
	}

}
